{% extends "chat_base.html" %}

{% block "title" %}using subscribe-group{% endblock %}

{% block introduction %}
<p>Point a second browser onto this URL, login as <em>mary</em> or <em>john</em> and check for message synchronization. They both are members of the group <em>chatters</em>.</p>
{% endblock introduction %}

{% block control_panel %}
	<button class="btn btn-primary" id="send_message">Send message</button>
	to
	<select class="form-control" id="group" style="display: inline-block; width: auto;">
	{% for group in groups %}
		<option value="{{ group.name }}">{{ group.name }}</option>
	{% endfor %}
	</select>
{% endblock control_panel %}

{% block script_panel %}
<script type="text/javascript">
jQuery(document).ready(function($) {
	var ws4redis = WS4Redis({
		uri: '{{ WEBSOCKET_URI }}foobar?subscribe-group',
		receive_message: receiveMessage,
		heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
	});
	var billboard = $('#billboard');

	$("#text_message").keydown(function(event) {
		if (event.keyCode === 13) {
			event.preventDefault();
			sendMessage();
		}
	});

	$('#send_message').click(sendMessage);

	// send message to the server using Ajax
	function sendMessage() {
		$.post('{% url "group_chat" %}', {
			group: $('#group').val(),
			message: $('#text_message').val()
		});
	}

	// receive a message though the Websocket from the server
	function receiveMessage(msg) {
		billboard.append('<br/>' + msg);
		billboard.scrollTop(billboard.scrollTop() + 25);
	}
});
</script>
{% endblock script_panel %}
